var md5 = require('../HttpUtils/md5.js');
var uuid = require('../HttpUtils/uuid.modified.js');
export default {
  data: {
    httpRes: []
  },
  func: {
    httpGet(url, dataJSON, errorMsg) {
      //参数中加入usereid,corpid
      var jsonData = JSON.parse(dataJSON);
      var uid = jsonData.userId;
      if (uid == null || undefined == uid || "" == uid) {
        jsonData["userId"] = getApp().globalData.userId;
      }
      jsonData["corpId"] = getApp().globalData.corpId;
      jsonData["timestamp"] = Date.parse(new Date()) / 1000;
      jsonData["nonce"] = this.lower(md5.md5Fun(Date.parse(new Date()) / 1000 + uuid.wxuuid()));
      jsonData["appKey"] = getApp().globalData.appKey;
      jsonData["sign"] = this.jsonSort(jsonData) + "&appSecret=" + getApp().globalData.appSecret;
      //md5 加密验证
      console.log(errorMsg + '加密前：------' + JSON.stringify(jsonData))
      var data = this.getMd5(JSON.stringify(jsonData));
      return new Promise(function (resolve, reject) {
        wx.request({
          url: url,
          method: 'POST',
          //headers: { 'Content-Type': 'multipart/form-data' },
          data: data ,
          dataType: 'json',
          success: (res) => {
            //如果需要解密,代码写在此处
            console.log(errorMsg.substr(0, errorMsg.length - 2))
            console.log(res);
            resolve(res);
          },
          fail: function (res) {
            // dd.alert({ content: errorMsg });
          },
          complete: function (res) {

          }
        });
      });

    },
    jsonSort: function (jsonObj) {
      let arr = [];
      for (var key in jsonObj) {
        arr.push(key)
      }
      arr.sort();
      let str = '';
      for (var i in arr) {
        str += arr[i] + "=" + jsonObj[arr[i]] + "&"
      }
      return str.substr(0, str.length - 1)
    },
    lower: function (str) {
      if (str != "") {
        return str.toLowerCase();
      }
    },
    //封装MD5加密
    getMd5: function (data) {
      //sign字段 md5加密
      var sign = "";
      if (data.indexOf('sign') != -1 && data.indexOf('nonce') != -1) {
        var jsonData = JSON.parse(data);
        // sign 字段加密
        if (JSON.parse(data).sign != "") {
          sign = this.lower(md5.md5Fun(JSON.parse(data).sign));
        }
        // nonce 字段加密 uuid32位唯一标识
        jsonData['sign'] = sign;

        return JSON.stringify(jsonData);
      }
    },

    getUrl(type, code, folderCode, name, topicId) {
      var detailUrl = "";
      if ("Pic" == type) {
        //图文跳转到图文详情页面
        detailUrl = '../newsDetail/newsDetail?folderCode=' + folderCode + '&code=' + code + '&name=' + name;
      } else if ("Series" == type) {
        //电视剧详情页面
        detailUrl = "../tvDetail/tvDetail?folderCode=" + folderCode + "&code=" + code + '&name=' + name;
      } else if ("Topic" == type) {
        //专题跳转到专题详情页面
        detailUrl = '../topicDetail/topicDetail?folderCode=' + folderCode + '&code=' + code + '&name=' + name;
      } else if ("topicDetail" == type) {
        //专题详情页面点击子内容详情地址
        topicId = null == topicId ? "" : topicId;
        detailUrl = '../shortVideoDetail/shortVideoDetail?fromPage=Topic&folderCode=' + folderCode + '&code=' + topicId + "&subCode=" + code + '&name=' + name;
      } else {
        //新闻资讯跳转到视频播放页面

        //当从专题详情界面跳转过来的时候栏目topicId为专题壳资产ID,
        detailUrl = '../shortVideoDetail/shortVideoDetail?fromPage=News&folderCode=' + folderCode + '&code=' + code + '&name=' + name;
      }
      return detailUrl;
    },
    
    //时间格式化
    formatDate(fmt, date) {
      date = null == date || "undefined" == typeof (date) ? new Date() : date;
      if ("string" == typeof (date)) {
        date = date.replace(/\-/g, '/');
        date = new Date(date);
      }
      var o = {
        "M+": date.getMonth() + 1,                 //月份   
        "d+": date.getDate(),                    //日   
        "h+": date.getHours(),                   //小时   
        "m+": date.getMinutes(),                 //分   
        "s+": date.getSeconds(),                 //秒   
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度   
        "S": date.getMilliseconds()             //毫秒
      };
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
      }
      for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
      }
      return fmt;
    },
    //显示消息的公共方法
    showPageMsg: function (msgType, msgContent) {
      // msgType="tips",表示显示一个错误,
      // msgType="alert"表示弹出alert框,
      // msgType="loading"表示显示加载框
      if ("alert" == msgType) {
        wx.showModal({ 
          content: msgContent,
          confirmText: 'YES',
          showCancel:false,
          confirmColor: '#1976D2',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定')
            } 
          }
        })
      } else if ("tips" == msgType) {
        wx.showToast({
          icon: 'none',
          title: msgContent,
          mask:true,
          duration: 2000,
          success: () => {
          }
        });
      } else if ("loading" == msgType) {
        wx.showLoading({
          title: '加载中',
        })
        setTimeout(function () {
          wx.hideLoading()
        }, 2000) 
      }
    },
  },

};
